package com.dlc.shop.user.platform.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.dlc.shop.bean.model.Category;
import com.dlc.shop.bean.param.CategoryScoreConfigParam;
import com.dlc.shop.bean.param.ScoreConfigParam;
import com.dlc.shop.common.annotation.SysLog;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.service.CategoryService;
import com.dlc.shop.service.SysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 积分基本配置信息
 * @author lhd
 */
@Tag(name = "积分基本配置信息")
@RestController
@RequestMapping("/user/scoreConfig")
@AllArgsConstructor
public class ScoreConfigController {

    private final SysConfigService sysConfigService;
    private final CategoryService categoryService;


    @GetMapping("/info/{key}")
    @PreAuthorize("@pms.hasPermission('user:scoreSonfig:info')")
    @Operation(summary = "获取配置信息" , description = "获取配置信息")
    @Parameter(name = "key", description = "参数名" )
    public ServerResponseEntity<ScoreConfigParam> info(@PathVariable("key") String key){
        ScoreConfigParam scoreParamDb = sysConfigService.getSysConfigObject(key,ScoreConfigParam.class);
        if(Objects.isNull(scoreParamDb)){
            ScoreConfigParam scoreParam = new ScoreConfigParam();
            addCategoryConfig(scoreParam);
            return ServerResponseEntity.success(scoreParam);
        }

        addCategoryConfig(scoreParamDb);
        if(scoreParamDb.getSignInScoreString() != null) {
            List<Integer> signScore = new ArrayList<>();
            String[] scores = scoreParamDb.getSignInScoreString().split(StrUtil.COMMA);
            for (String score : scores) {
                signScore.add(Integer.valueOf(score.trim()));
            }
            scoreParamDb.setSignInScore(signScore);
        }
        return ServerResponseEntity.success(scoreParamDb);
    }

    @SysLog("保存配置")
    @PostMapping
    @Operation(summary = "保存配置", description = "保存配置")
    @PreAuthorize("@pms.hasPermission('user:scoreSonfig:save')")
    public ServerResponseEntity<Void> save(@RequestBody @Valid ScoreConfigParam scoreConfigParam){
        this.addCategoryConfig(scoreConfigParam);
        sysConfigService.saveOrUpdateSysConfigService(scoreConfigParam,Constant.SCORE_CONFIG);
        return ServerResponseEntity.success();
    }



    private void addCategoryConfig(ScoreConfigParam scoreParam) {
        List<CategoryScoreConfigParam> params = new ArrayList<>();
        Map<Long, CategoryScoreConfigParam> categoryMap;
        if (CollUtil.isNotEmpty(scoreParam.getCategoryConfigs())) {
            categoryMap = scoreParam.getCategoryConfigs().stream().collect(Collectors.toMap(CategoryScoreConfigParam::getCategoryId, c->c));
        } else {
            categoryMap = new HashMap<>(0);
        }
        List<Category> categories = categoryService.listByShopIdAndParentIdAndGrade(Constant.PLATFORM_SHOP_ID, Constant.CATEGORY_ID, 1);
        for (Category category : categories) {
            CategoryScoreConfigParam param = categoryMap.get(category.getCategoryId());
            if (Objects.isNull(param)) {
                param = new CategoryScoreConfigParam();
                param.setCategoryId(category.getCategoryId());
                param.setGetScoreLimit(1.0);
                param.setUseScoreLimit(1.0);
            }
            param.setCategoryName(category.getCategoryName());
            params.add(param);
        }
        scoreParam.setCategoryConfigs(params);
    }

}
